package controllers

import (
	"cang/cache"
	"cang/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type CangController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}

func (c *CangController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 2)
	i := (page - 1) * size
	var cang []models.Cang
	get, _ := cache.Rdb.Get(cache.Ctx, "cang_list").Result()
	if get != "" {
		json.Unmarshal([]byte(get), &cang)
	} else {
		models.DB.Debug().Offset(i).Limit(size).Order("id desc").Find(&cang)
		maeshal, _ := json.Marshal(cang)
		cache.Rdb.Set(cache.Ctx, "cang_list", maeshal, time.Minute*2)
	}

	c.Data["json"] = Res{
		Code: 200,
		Data: cang,
		Msg:  "展示成功",
	}
	c.ServeJSON()
	return

}
func (c *CangController) Show() {
	id, _ := c.GetInt("id")
	var cang models.Cang

	models.DB.Debug().Where("id=?", id).First(&cang)

	c.Data["json"] = Res{
		Code: 200,
		Data: cang,
		Msg:  "详情查询成功",
	}
	c.ServeJSON()
	return

}
